import { useAuthStore, usePermissionStore } from '@/store'

const WHITE_LIST = ['/login', '/404']
export function createPermissionGuard(router) {
  router.beforeEach(async (to) => {
    const authStore = useAuthStore()
    const token = authStore.accessToken
    const { menus } = usePermissionStore()
    /** 没有token */
    if (!token) {
      if (WHITE_LIST.includes(to.path)) return true
      return { path: 'login', query: { ...to.query, redirect: to.path } }
    }
    if (menus.length === 0) {
      authStore.resetToken()
      return { path: 'login' }
    }

    // 有token的情况
    if (to.path === '/login') return { path: '/' }
    if (WHITE_LIST.includes(to.path)) return true
    const routes = router.getRoutes()
    if (routes.find((route) => route.name === to.name)) return true
    return { name: '404', query: { path: to.fullPath } }
  })
}
